'use strict';

const knex = require('../conf/db');
const Router = require('koa-router');
const { token } = require('../util/token');
const { system } = require('../conf/tables');
const { encode, decode } = require('jwt-simple');

module.exports = (app) => {
    const router = new Router({
        prefix: '/login'
    });
    router.post('/user', async(ctx, next) => {
        const userinfo = await knex(system.userinfo).where(ctx.request.fields);
        const _token = await token(app);
        ctx.body = {
            status: userinfo.length ? 'success' : 'failed',
            token: userinfo.length ? encode(userinfo.pop(), _token.pop().code) : ''
        }
    });

    app.use(router.routes())
        .use(router.allowedMethods());
}